package com.epalmpay.controller.apiweixin;

import java.io.IOException;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epalmpay.dto.terminalmanage.DeviceOutDTO;
import com.epalmpay.entity.*;
import com.epalmpay.service.weixin.IWxApiMallService;
import com.epalmpay.status.Rescode;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.epalmpay.commom.BaseController;
import com.epalmpay.dto.member.MemberOutDTO;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.ITokenService;
import com.epalmpay.service.weixin.IWxApiService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.util.PageData;
import com.epalmpay.util.Response;
import com.epalmpay.util.StringUtil;
import com.epalmpay.util.Token;
import com.epalmpay.util.Tools;
import com.epalmpay.enumdef.BizEnum;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

/**
 * 
 * 类名称：WechatController.java 类描述： 微信公众号首页开发网页授权
 * 
 * @author zsj 创建时间：2017年5月18日
 */
@Controller
@RequestMapping(value = "/api/oAuth2")
public class WechatOAuth2Controller extends BaseController {

	@Autowired
	protected WxService wxService;

	@Autowired
	protected IWxBaseService wxBaseService;
	@Resource
	private IMemberService memberService;
	@Resource
	private IGroupService groupService;

	@Resource
	private IWxApiService wxApiService;

	@Value("${oauth_Url}")
	private String oauthUrl;

	@Autowired
	private ITokenService tokenService;
    
    @Value("${WX_Key}")
    private String wXKey;

	@Resource
	private IWxApiMallService wxApiMallService;

	@RequestMapping(value = "index", method = { RequestMethod.GET, RequestMethod.POST })
	public void wechatOpenId(HttpServletRequest request, HttpServletResponse response,String groupId) throws Exception {
		logBefore(logger, "------------------------------------获取微信openId第1步开始------------------------------------");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.valueOf(groupId)));
		String referer = request.getHeader("Referer");
		String whref = request.getParameter("whref");
		String state = "";

		Group group = groupService.selectGroupInfo(Long.valueOf(groupId));
		String url = HOME_URL + "/api/oAuth2/wxCallbackCode";
		if(group.getWebsite() != null) {//如果有自定义域名
			url = group.getWebsite() + "/EBosService/api/oAuth2/wxCallbackCode";
		}
		// String
		// urltest="http://sbs-test.eboss007.com/EBosService/api/oAuth2/wxCallbackCode";
		if (referer == null) {
			if (group.getWebsite() != null) {//如果有自定义域名
				referer = String.format("%s/" + groupId + "/index.html", group.getWebsite());
			} else {
				// 首页 html
				referer = String.format("%s/" + groupId + "/index.html", ROOT_HOME_URL);
			}
		}
		state = java.net.URLEncoder.encode(referer, "utf-8");

		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.valueOf(groupId)));
		String href = wxService.oauth2buildAuthorizationUrl(url+"?groupId="+groupId, WxConsts.OAUTH2_SCOPE_BASE, state);
		logBefore(logger, "------------------------------------获取微信openId第1步结束-----------------------------------");
		response.sendRedirect(href);
	}

	@RequestMapping(value = "wxCallbackCode", method = { RequestMethod.GET, RequestMethod.POST })
	public String wxCallbackCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logBefore(logger, "------------------------------------获取微信openId第2步开始------------------------------------");
		PageData pd = new PageData();
		pd = this.getPageData();
		String groupId = pd.getString("groupId");
		String code = pd.getString("code");
		String state = pd.getString("state");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
		String openId = wxMpOAuth2AccessToken.getOpenId();
		if (Tools.isEmpty(openId)) {
			response.sendRedirect(state);
		} else {
			MemberOutDTO member = memberService.queryAmountOpenId(openId, groupId);
			// 查询是否开通钱包 即查询大商户是否开通分销商管理模块 memberId正式环境做ace加密处理
			Boolean flag = groupService.selectGroupModel(Long.parseLong(groupId));
			// 会员是否签到
			Integer signState = wxApiService.querytodaymemberSign(member.getId(), Long.parseLong(groupId));
			
			StringBuffer bf = new StringBuffer();
			String begin=state.contains("?")?state:state+"?";
			
			
			Long memberId = member.getId();
			// String memberIdAce=AES.AESEncode(wXKey, memberId.toString());
			// String memberId=AES.AESDncode(wXKey, memberIdAce);
			Token token = tokenService.getTokenInfo(memberId + "");
			if (token != null) {
				if (flag) {
								if (Tools.isEmpty(member.getVirtualCard())) {
									bf.append(begin).append("&memberId=").append(memberId).append("&groupId=").append(groupId).append("&openedStatus=1").append("&loginStatus=0")
									.append("&signState=").append(signState).append("&token=").append(token.getValue()).append("&redPacket=0");
									
								} else {
									// 显示余额
									   bf.append(begin).append("&memberId=").append(memberId).append("&groupId=").append(groupId).append("&openedStatus=1").append("&loginStatus=1")
									   .append("&signState=").append(signState).append("&curBal=").append(member.getCurBal())
									   .append("&token=").append(token.getValue()).append("&redPacket=").append(member.getRedPacket());
								}
				} else {
					bf.append(begin).append("&memberId=").append(memberId).append("&groupId=").append(groupId).append("&openedStatus=0")
					   .append("&signState=").append(signState).append("&token=").append(token.getValue()).append("&redPacket=0");
				}
				
				bf.append("&random=").append(Tools.getRandomNumABC(6));
				response.sendRedirect(bf.toString());
			} else {
				logBefore(logger, "------------------------------------生成签名失败------------------------------------");
				return null;
			}
		}
		logBefore(logger, "------------------------------------获取微信openId第2步结束------------------------------------");
		return null;
	}

	/**
	 * 生成JS-SDK权限验证的签名
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/JsSdk", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Response getpaycrcode(HttpServletRequest request, HttpServletResponse response, String groupId, String url) throws Exception {
		logBefore(logger, "生成JS-SDK权限验证的签名");
		if (Tools.isEmpty(groupId)) {
			return Response.getError("groupId不能为空");
		}
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		String jsapi_ticket = wxService.getJsapiTicket();
		String noncestr = StringUtil.create_nonce_str();
		String timestamp = StringUtil.create_timestamp();
		String signature = StringUtil.wxSignature_JS(jsapi_ticket, noncestr, timestamp, url);
		HashMap<String, String> map = new HashMap<String, String>();
		System.out.println(signature);
		map.put("appId", wxService.getWxMpConfigStorage().getAppId());
		map.put("timestamp", timestamp);
		map.put("nonceStr", noncestr);
		map.put("signature", signature);
		return Response.getSuccess(map);
	}
	
	 /**
	  * 关注跳转页面
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	@RequestMapping(value = "urlSubscribe", method = { RequestMethod.GET, RequestMethod.POST })
	public void urlSubscribe(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logBefore(logger, "用户关注url跳转url");
		String url = null;
		String openId=request.getParameter("openId");
		String type=request.getParameter("type");
		Member member=memberService.selectByOpenId(openId);
		if(member==null){
			response.sendRedirect(url);
		}
		String memberId=member.getId()+""; 
		Token token = tokenService.getTokenInfo(memberId);
		if(member.getWalletStatus()==1){
			switch (BizEnum.ScancrcodeType.fromType(Integer.valueOf(type))) { 
			case subscribe:
				url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,ROOT_HOME_URL);
				break;
			case agentSubscribe:
				url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,ROOT_HOME_URL);
				break;
			case ShopsubScribe:
				url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,ROOT_HOME_URL);
				break;	
			case memberSubscribe:
				url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,ROOT_HOME_URL);
				break;	
			case posConsumeSend:
				//判断该红包是否领取
			    url=String.format("%s/"+member.getGroupId()+"/redpacket_list.html",ROOT_HOME_URL);
				break;	
			case posRedEnvelope:
			    url=String.format("%s/"+member.getGroupId()+"/redpacket_list.html",ROOT_HOME_URL);
				break;	
			default:
				break;
		  }
		}else{
			//注册首页
			url=String.format("%s/"+member.getGroupId()+"/register.html?memberId="+memberId+"&groupId="+member.getGroupId()
			        +"&openedStatus=1&loginStatus=0"
					+ "&signState=0&token="+ token.getValue()
					+ "&redPacket=0"
			        ,ROOT_HOME_URL);
			}
			response.sendRedirect(url);
	}
	
	
	@RequestMapping(value = "getDiscount", method = { RequestMethod.GET, RequestMethod.POST })
	public void getDiscount(HttpServletRequest request, HttpServletResponse response,String groupId,String id,String type) throws Exception {
		logBefore(logger, "-----获取优惠微信openId第1步开始");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.valueOf(groupId)));
		String referer = request.getHeader("Referer");
		String state = "";
		String url = HOME_URL + "/api/oAuth2/getDiscountbackCode";
		if (referer == null) {
			referer=String.format("%s/"+groupId+"/index.html",ROOT_HOME_URL);
		}
		state = java.net.URLEncoder.encode(referer, "utf-8");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.valueOf(groupId)));
		String href=null;
		if(type.equals("1")){
			href = wxService.oauth2buildAuthorizationUrl(url + "?groupId=" + groupId+"&id="+id+"&type="+type, WxConsts.OAUTH2_SCOPE_BASE, state);
		}else if(type.equals("2")){
			href = wxService.oauth2buildAuthorizationUrl(url + "?groupId=" + groupId+"&type="+type, WxConsts.OAUTH2_SCOPE_BASE, state);
		}
		logBefore(logger, "-获取优惠openId第1步结束");
		response.sendRedirect(href);
	}

	
	@RequestMapping(value = "getDiscountbackCode", method = { RequestMethod.GET, RequestMethod.POST })
	public String getDiscountbackCode(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		logBefore(logger, "获取优惠openId第2步开始");
		PageData pd = new PageData();
		pd = this.getPageData();
		String groupId = pd.getString("groupId");
		String code = pd.getString("code");
		String state = pd.getString("state");
		String id = pd.getString("id");
		String type = pd.getString("type");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
		String openId = wxMpOAuth2AccessToken.getOpenId();
		if (Tools.isEmpty(openId)) {
			response.sendRedirect(state);
		} else {
			Member member=memberService.selectByOpenId(openId);
			if(member==null){
				GroupWxconfig groupWxconfig=groupService.selectGroupWxconfigId(Long.valueOf(groupId));
				if(groupWxconfig!=null){
					model.addAttribute("imageUrl", groupWxconfig.getWxQrcodeUrl());
					return "subscribe";
				}else{
					model.addAttribute("msg", "请先关注公众号再进行操作");
					 return "payError";
				}
			}else{
				String url=null;
				if(type.equals("1")){//优惠券
					 url =String.format("%s/"+member.getGroupId()+"/coupon_full_detail.html?id="+id+"&memberId="+member.getId(),ROOT_HOME_URL);
				}else if(type.equals("2")){//红包
					url =String.format("%s/"+member.getGroupId()+"/redpacket_list.html?id="+id+"&memberId="+member.getId(),ROOT_HOME_URL);
				}
				response.sendRedirect(url);
			}
			
		}
		logBefore(logger, "获取优惠openId第2步结束");
		return null;
	}


	/**
	 * 授权首页
	 * @param deskcardCode  台卡编号
	 * @param deskcardId    主键ID
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goodDetailShare", method = {RequestMethod.GET,RequestMethod.POST} )
	public String goodDetailShare(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logBefore(logger, "商品分享授权首页"+HOME_URL);
		logBefore(logger, "商品分享授权首页"+ROOT_HOME_URL);
		String type = request.getHeader("user-agent");

		Long groupId = Long.parseLong(request.getParameter("groupId"));//商圈编号
		String goodId = request.getParameter("gid");//商品编号
		String memberId = request.getParameter("memberid");//分享者编号
		WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage=null;
		try {
			wxMpInMemoryConfigStorage = wxBaseService.getTokenByGroupId(groupId);
		} catch (Exception e1) {
			e1.printStackTrace();
			return "payError";
		}
		try {
			if (type.toLowerCase().indexOf("micromessenger") >= 0) {
				String  url=HOME_URL+"/api/weixin/mall/goodDetailIndex";
				wxService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
				String href = wxService.oauth2buildAuthorizationUrl(
						url+"?gid="+goodId+"&groupId="+groupId+"&memberid="+memberId,
						WxConsts.OAUTH2_SCOPE_BASE, "");
				logBefore(logger, "------------------------------------获取微信openId第1步结束-----------------------------------");
				response.sendRedirect(href);
				return null;
			}else
			if (type.toLowerCase().indexOf("alipayclient") >= 0) {
				// 支付宝
				String path="";//HOME_URL+"/api/pay/tkAliPayIndex";
				//String name = java.net.URLEncoder.encode(device.getMerchantName(),"utf-8");
				//String path = url+"?deskcardCode="+deskcardCode+"&deskcardId="+deskcardId+"&shopId="+device.getShopId()+"&merchantName="+name;
				logBefore(logger, "支付宝授权url"+path);
				try {
					response.sendRedirect(path);
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "payError";
		}
		// 请用微信或者支付宝扫描
		logBefore(logger, "----------------非微信或支付宝扫描---------------------");
		return "payError";
	}


	

}
